﻿using Hangfire;
using Hangfire.Dashboard.BasicAuthorization;
using Hangfire.HttpJob;
using Hangfire.MySql;
using Hangfire.SqlServer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System.Transactions;

namespace ED.HangFire
{
    public static class HangFireExtensions
    {
        public static IServiceCollection AddCustomHangFire(this IServiceCollection services, string sqlConnection)
        {
            services.AddHangfire(configuration => configuration
    .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
    .UseSimpleAssemblyNameTypeSerializer()
    .UseRecommendedSerializerSettings()
    .UseStorage(new MySqlStorage(
        sqlConnection,
        new MySqlStorageOptions
        {
            TransactionIsolationLevel = IsolationLevel.ReadCommitted,
            QueuePollInterval = TimeSpan.FromSeconds(15),
            JobExpirationCheckInterval = TimeSpan.FromHours(1),
            CountersAggregateInterval = TimeSpan.FromMinutes(5),
            PrepareSchemaIfNecessary = true,
            DashboardJobListLimit = 50000,
            TransactionTimeout = TimeSpan.FromMinutes(1),
            TablesPrefix = "Hangfire"
        })).UseHangfireHttpJob());
            services.AddHangfireServer();//必须加，不加无法执行
            return services;
        }

        public static WebApplication UseHangFire(this WebApplication app)
        {
            app.UseHangfireDashboard("/hangfire", new DashboardOptions
            {
                Authorization = new BasicAuthAuthorizationFilter[] {
                      new BasicAuthAuthorizationFilter(new BasicAuthAuthorizationFilterOptions(){
                           SslRedirect=false,
                            RequireSsl=false,
                             Users=new BasicAuthAuthorizationUser[]{
                                  new BasicAuthAuthorizationUser(){
                                      Login="admin",
                                      PasswordClear="123456"
                                  }
                             }
                      })
                }
            });
            return app;
        }
    }
}